package com.ebelter.seneo.ui.activitys;

import android.text.Selection;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ebelter.btcomlib.models.db.products.seneo.SeneoUserinfos;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.LoginResponseSubInfo;
import com.ebelter.btcomlib.utils.MD5Utils;
import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.seneo.R;
import com.ebelter.seneo.contants.IUserContant;
import com.ebelter.seneo.models.SeneoDbUtils;
import com.ebelter.seneo.models.SeneoNet;
import com.ebelter.seneo.utils.SeneoUtils;

import java.util.List;

public class SeneoLoginActivity extends SeneoBaseActivity {


    public static final String TAG = "SeneoLoginActivity";
    EditText lg_email_ed;
    EditText lg_psw_ed;
    ImageView lg_psw_iv;
    TextView lg_forget_psw_tv;
    TextView lg_register_tv;


    private boolean displayPsw;


    private LinearLayout lg_nick_ll;
    private LinearLayout lg_psw_ll;

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_seneo_login;
    }

    @Override
    protected void initView() {
        lg_email_ed = findViewById(R.id.lg_email_ed);
        lg_psw_ed = findViewById(R.id.lg_psw_ed);
        lg_psw_iv = findViewById(R.id.lg_psw_iv);
        lg_forget_psw_tv = findViewById(R.id.lg_forget_psw_tv);
        lg_register_tv = findViewById(R.id.lg_register_tv);
        lg_nick_ll = findViewById(R.id.lg_nick_ll);
        lg_psw_ll = findViewById(R.id.lg_psw_ll);
        updatePswModel();

        lg_nick_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SeneoUtils.showSoftInputFromWindow(SeneoLoginActivity.this, lg_email_ed);
                Selection.setSelection(lg_email_ed.getText(), lg_email_ed.getText().length());
            }
        });
        lg_psw_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SeneoUtils.showSoftInputFromWindow(SeneoLoginActivity.this, lg_psw_ed);
                Selection.setSelection(lg_psw_ed.getText(), lg_psw_ed.getText().length());
            }
        });


        ViewUtils.setEdInputFilters(lg_email_ed);

    }

    @Override
    protected void initData() {


        String loginName = UserSpUtil.readString(IUserContant.IUser.loginName);
        String psw2 = UserSpUtil.readString(IUserContant.IUser.psw2);

        if (!TextUtils.isEmpty(loginName)) {
            ViewUtils.setTextViewStr(lg_email_ed, loginName);
            Selection.setSelection(lg_email_ed.getText(), lg_email_ed.getText().length());
        }
        if (!TextUtils.isEmpty(psw2)) {
            ViewUtils.setTextViewStr(lg_psw_ed, psw2);
        }
    }

    public void login(View view) {
        final String name = lg_email_ed.getText().toString().trim();
        final String psw = lg_psw_ed.getText().toString().trim();
        //  String psw = login_mypsw_cb.getText();

        if (TextUtils.isEmpty(name)) {
            ToastUtil.show(R.string.Nikename_cannot_be_empty);
            return;
        }
        if (TextUtils.isEmpty(psw)) {
            ToastUtil.show(R.string.The_password_cannot_be_empty);
            return;
        }
        if (!NetUtils.available()) {
            ToastUtil.show(R.string.Network_error);
            return;
        }


        //showLoadingDialog(StringUtils.getResStr(R.string.Log_in));
        final String md5psw = MD5Utils.getMd5(psw);
        SeneoNet.getIntance().loginRequest(this, false, name, md5psw, new HttpResponse<LoginResponseSubInfo>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, LoginResponseSubInfo loginResponse, String s) {
                // dissLoadingDialog();
                LogUtils.i2(TAG, "----登录=loginResponse=" + loginResponse);
                // {resultData=null, responseStr='null', resultCode=-1, resultMessage='不存在的email或者昵称'}
                if (isRequestSuccess) {
                    if (loginResponse.resultCode == 0) {

                        UserSpUtil.writeString(IUserContant.IUser.loginName, name);
                        UserSpUtil.writeString(IUserContant.IUser.psw, md5psw);
                        UserSpUtil.writeString(IUserContant.IUser.psw2, psw);
                        //登录成功
                        saveUserDatas(loginResponse);
                        //ToastUtil.show("Login successfully!");
                        SeneoMainActivity.openSeneoMainActivity(SeneoLoginActivity.this, false);
                        finish();
                    } else if (loginResponse.getResultCode() == 109) {//109是：不存在的email或者昵称
                        ToastUtil.show(R.string.mail_nickname_no_exist);
                    } else if (loginResponse.getResultCode() == 111 || loginResponse.getResultCode() == -1) {//111密码错误
                        ToastUtil.show(R.string.psw_error);
                    } else if (loginResponse.getResultCode() == 110) {//服务器异常
                        ToastUtil.show(R.string.An_exception_occurred_on_the_server);
                    }

                } else {
                    ToastUtil.show(R.string.Network_connection_error);
                }
            }
        });
    }


    //保存登录用户数据
    public static void saveUserDatas(LoginResponseSubInfo resultData) {
        if (resultData == null) {
            return;
        }
        SeneoDbUtils.deleteTable(SeneoUserinfos.class);//先删除整个用户信息表

        List<LoginResponseSubInfo.ResultDataBean> users = resultData.resultData;
        if (users != null) {
            for (int i = 0; i < users.size(); i++) {
                LoginResponseSubInfo.ResultDataBean user = users.get(i);
                String nickName = user.nickName;
                String email = user.email;
                String birthday = user.birthday;
                int height = user.height;
                long mainId = user.mainId;
                long userId = user.userId;
                int impedance = user.impedance;
                int profession = user.profession;
                int sex = user.sex;

                SeneoUserinfos userinfos = new SeneoUserinfos();
                if (userId > 0 && mainId == 0) {
                    //主用户
                    userinfos.isHost = true;
                    userinfos.host_id = userId;
                } else {
                    userinfos.isHost = false;
                    userinfos.host_id = mainId;
                }
                userinfos.user_id = userId;
                userinfos.nickName = nickName;
                userinfos.email = email;
                userinfos.height = height;
                userinfos.birthday = birthday;
                userinfos.impedance = impedance;
                userinfos.athlete = profession;
                userinfos.sex = sex;
                userinfos.targetWeight = user.targetWeight;
                userinfos.currentWeight = user.weight;
                userinfos.save();
            }
        }


    }

    //密码显示模式改变
    public void pswdisChange(View view) {
        displayPsw = !displayPsw;
        updatePswModel();
    }

    private void updatePswModel() {
        if (displayPsw) {
            //密码可见
            lg_psw_ed.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            ViewUtils.setImageResource(lg_psw_iv, R.drawable.ic_psw2);
            Selection.setSelection(lg_psw_ed.getText(), lg_psw_ed.getText().length());
        } else {
            //密码不可见
            lg_psw_ed.setTransformationMethod(PasswordTransformationMethod.getInstance());
            ViewUtils.setImageResource(lg_psw_iv, R.drawable.ic_psw1);
            Selection.setSelection(lg_psw_ed.getText(), lg_psw_ed.getText().length());
        }
    }

    public void forgetpsw(View view) {
        SeneoModifyPswActivity.openSeneoModifyPswActivity(this, null, null);
    }

    //打开注册界面
    public void register(View view) {
        SeneoAddInfoActivity.openSeneoAddInfoActivity(this, 1002, SeneoAddInfoActivity.CMD_register, StringUtils.getResStr(R.string.signin), 0);
    }


}
